package cn.zyg.ymcc.exception;

import cn.zyg.ymcc.enums.GlobalExceptionCode;
import cn.zyg.ymcc.result.JSONResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

// 此注解的作用是对全局的controller进行增强 主动捕捉所以异常
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    public JSONResult customException(Exception e) {
        e.printStackTrace();
        log.info("全局的异常捕捉 Exception");
        return JSONResult.error(GlobalExceptionCode.ERROR);
    }

    @ExceptionHandler(GlobalCustomException.class)
    public JSONResult customException(GlobalCustomException e) {
        return JSONResult.error(e);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JSONResult customException(MethodArgumentNotValidException e) {
        e.printStackTrace();
        log.error("全局统一异常捕捉到错误，错误类型为MethodArgumentNotValidException，错误信息为：{}", e.getMessage());
        // return JSONResult.error(GlobalExceptionCode.ERROR.getMessage(), GlobalExceptionCode.ERROR.getCode());
        StringBuffer sb = new StringBuffer();
        e.getBindingResult().getAllErrors().forEach(obj->{
            sb.append(obj.getDefaultMessage()).append(",");
        });
        return JSONResult.error(sb.toString(), "1000");
    }
}
